package com.wwt.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.wwt.server.pojo.*;
import com.wwt.server.service.*;
import com.wwt.server.vo.Result;
import com.wwt.server.vo.ResultPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Tao
 * @since 2021-12-05
 */
@RestController
@Api(tags = "员工管理")
@RequestMapping("/personnel/emp")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private INationService nationService;
    @Autowired
    private IPoliticsStatusService politicsStatusService;
    @Autowired
    private IJoblevelService joblevelService;
    @Autowired
    private IPositionService positionService;
    @Autowired
    private IDepartmentService departmentService;

    @GetMapping("/")
    @ApiOperation("获取所有员工")
    public ResultPage getAllEmp(@RequestParam(defaultValue = "1") Integer currentPage,
                                @RequestParam(defaultValue = "10") Integer size,
                                Employee employee,
                                LocalDate[] dates) { //合同起始日期范围
        return employeeService.getAllEmp(currentPage, size, employee, dates);
    }

    @GetMapping("/nations")
    @ApiOperation(value = "获取所有民族")
    public List<Nation> getAllNations() {
        return nationService.list();
    }

    @GetMapping("/politicsstatus")
    @ApiOperation(value = "获取所有政治面貌")
    public List<PoliticsStatus> getAllPoliticsstatus() {
        return politicsStatusService.list();
    }

    @GetMapping("/joblevels")
    @ApiOperation(value = "获取所有职称")
    public List<Joblevel> getAllJoblevels() {
        return joblevelService.list();
    }

    @GetMapping("/positions")
    @ApiOperation(value = "获取所有职位")
    public List<Position> getAllPositions() {
        return positionService.list();
    }

    @GetMapping("/deps")
    @ApiOperation(value = "获取所有部门")
    public List<Department> getAllDepartment() {
        return departmentService.list();
    }

    //添加工号自动为最大工号加1
    @GetMapping("/maxWorkID")
    @ApiOperation(value = "获取最大工号")
    public Result getMaxWorkId() {
        return employeeService.getMaxId();
    }

    @ApiOperation(value = "添加员工")
    @PostMapping("/")
    public Result addEmp(@RequestBody Employee employee) {
        return employeeService.insertEmp(employee);

    }

    @ApiOperation(value = "修改员工信息")
    @PutMapping("/")
    public Result updateEmp(@RequestBody Employee employee) {
        return employeeService.updateEmp(employee);
    }

    @ApiOperation(value = "删除员工")
    @DeleteMapping("/{id}")
    public Result deleteEmp(@PathVariable Integer id) {
        boolean result = employeeService.removeById(id);
        if (result)
            return Result.success("删除成功！");
        return Result.fail("删除失败！");
    }

    @ApiOperation("导出员工数据")
    @GetMapping(value = "/export", produces = "application/octet-stream") //二进制形式
    public void exportEmp(HttpServletResponse response) {
        List<Employee> exportEmp = employeeService.getExportEmp(null);
        ExportParams params = new ExportParams("员工信息表", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, exportEmp);
        ServletOutputStream stream = null;
        try {
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("content-disposition", "attachment;filename=" +
                    URLEncoder.encode("员工表.xls", "UTF-8"));
            stream = response.getOutputStream();
            workbook.write(stream);
            stream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导入员工数据")
    @ApiImplicitParam(name = "file", value = "文件上传", dataType = "MultipartFile")
    @PostMapping("/import")
    public Result importEmp(MultipartFile file) {
        List<Nation> nationList = nationService.list();
        List<Department> departmentList = departmentService.list();
        List<Joblevel> joblevelList = joblevelService.list();
        List<Position> positionList = positionService.list();
        List<PoliticsStatus> politicsStatusList = politicsStatusService.list();
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(1);
        params.setHeadRows(2);
        try {
            //InputStream inputStream = file.getInputStream();
            try {
                List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
                list.forEach(employee -> {
                            Nation nation = nationList.get(nationList.indexOf(new Nation(employee.getNation().getName())));
                            employee.setNationid(nation.getId());
                            Department department = departmentList.get(departmentList.indexOf(new Department(employee.getDepartment().getName())));
                            employee.setDepartmentid(department.getId());
                            Joblevel joblevel = joblevelList.get(joblevelList.indexOf(new Joblevel(employee.getJoblevel().getName())));
                            employee.setJoblevelid(joblevel.getId());
                            Position position = positionList.get(positionList.indexOf(new Position(employee.getPosition().getName())));
                            employee.setPosid(position.getId());
                            PoliticsStatus politicsStatus = politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName())));
                            employee.setPoliticid(politicsStatus.getId());
                        }
                );
                boolean b = employeeService.saveBatch(list);
                if (b)
                    return Result.success("插入成功！");
                return Result.fail("插入失败，请重新插入!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail("插入失败，请重新插入！");
    }
}